var interval=5;
var data1;
var routeData,route;
var cirPts;
var responseCode1;
var ptno=/^[0-9]*$/;
var zoomLevel1;
var myMarker = [];
var myGMarker = [];
var gmarkers = [];
var imeiArr = [];
var mapType;
var t1=null;
var side_bar_html = "";
var progressBar;
var geoData="";
var geoPointName= "";
var bubInter = 3;
var tmpDist = -1,plDist;
var playMarkId = [];
var tooltip;
var parameterData;

function showTooltip(marker) {
    tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x ,- offset.y + point.y )); 
	//var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - 35,- offset.y + point.y +anchor.y)); 
	//var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x - (width+20),- offset.y + point.y -anchor.y)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function getAllVehicle(date_offline,sessionid)
{
	showMessage('Getting Vehicles...');
	zoomLevel=5;
	ajax1.requestFile = 'showAllDevice.php?date_offline='+date_offline + '&sessionid='+sessionid;
	//document.write(ajax1.requestFile);
	showMessage('Loading ...');
	ajax1.onCompletion = function(){loadAllGPSLocations(date_offline)};
	ajax1.runAJAX();
	//GDownloadUrl(url, loadAllGPSLocations);
}

function getOneVehicle(url)
{
	zoomLevel=15;	
	showMessage('Getting map...');
	ajax1.requestFile = url;
	//document.write(ajax1.requestFile);
	showMessage('Loading ...');
	ajax1.onCompletion = function(){updateAllGPSLocations()};
	ajax1.runAJAX();
	//GDownloadUrl(url, updateAllGPSLocations);
	showMessage('Loading...');
}
function getAddress(lat,long,div)
{
	var addr="";
	address=((lat)+","+(long));
	var geocoder2 = new GClientGeocoder();
	geocoder2.getLocations(address, function(response) {
	  if (!response || response.Status.code != 200) {
		//alert("Status Code:" + response.Status.code);
		document.getElementById(div).innerHTML= "Status Code: not identified";
	  } else {
		place = response.Placemark[0];
	
		addr=place.address;
		return addr;
	}
	});
}
function ListParameters(i1,marker1)
{
deleteRow('paramTable')
//var str = marker1[i1].getAttribute("other");
var devmodel = marker1[i1].getAttribute("deviceModel");
/*if(marker1[i1].getAttribute("fuelPort") != 0)
{
	var fuel = getDataFromParam(str,marker1[i1].getAttribute("fuelPort"));

	if(fuel.length >= 3)
	{
		fuelVal = marker1[i1].getAttribute("fuelVoltage").split("@")
		fuelLtr = marker1[i1].getAttribute("fuelLtr").split("@")

		finVal =  getClosestElement(fuelVal, fuelLtr, (fuel/1000)) ;
		fuelGauge.SetFuel(finVal);
	}
	else
	{
		fuelGauge.SetFuel(0);
	}
}
else
{
	$('li#fuelIMG').hide();
}
var otherPort1 = marker1[i1].getAttribute("otherPort");
otherPort2 = otherPort1.split("#");
var dispParam = "";

for(k=0; k<(otherPort2.length)-1;k++)
{
	otherPort3 = otherPort2[k].split("_");

	if(otherPort3[1] != 0)
	{
		//alert(k+" "+otherPort2[k]+" "+otherPort3)
		var resultPort = getDataFromParam(str,otherPort3[1])
		if(resultPort == 1)
		{
			var table = document.getElementById('paramTable');
 
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
 
            var cell1 = row.insertCell(0);
			cell1.innerHTML = "<b>"+otherPort3[0]+"</b>";
 
            var cell2 = row.insertCell(1);
            cell2.innerHTML = '<img src=images/icons/ignition-on.png width=20 height=20 border=0 />';

			//dispParam += '<img src=images/icons/ignition-on.png width=20 height=20 border=0 />';
		}
		else if(resultPort == 0)
		{
			var table = document.getElementById('paramTable');
 
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
 
            var cell1 = row.insertCell(0);
			cell1.innerHTML = "<b>"+otherPort3[0]+"</b>";
 
            var cell2 = row.insertCell(1);
            cell2.innerHTML = '<img src=images/icons/ignition-off.png width=20 height=20 border=0 />';
			//dispParam += '<img src=images/icons/ignition-off.png width=20 height=20 border=0 />';
		}
	}
	
}*/
var table = document.getElementById('paramTable');
 
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
cell1.innerHTML = "<b>Distance</b>";

var cell2 = row.insertCell(1);
cell2.innerHTML = marker1[i1].getAttribute("distance")+" km(s)";


if(marker1[i1].getAttribute("digInputLabel") != '' && marker1[i1].getAttribute("digInputValue") != '')
{
	var inpLabel = marker1[i1].getAttribute("digInputLabel").split("#");
	var inpValue = marker1[i1].getAttribute("digInputValue").split("#");
	for(u = 0 ; u < inpLabel.length -1 ; u++)
	{
		var table = document.getElementById('paramTable');
		var rowCount = table.rows.length;
		var row = table.insertRow(rowCount);

		var inpLabelCell = row.insertCell(0);
		inpLabelCell.innerHTML = "<b>"+inpLabel[u]+"</b>";
		
		var inpValueCell = row.insertCell(1);
		inpValueCell.innerHTML = '<img src=images/icons/on-'+inpValue[u]+'.png width=20 height=20 border=0 />';
	}

}
/*if(marker1[i1].getAttribute("analogLabel") != '' && marker1[i1].getAttribute("analogValue") != '')
{
	var index = $('#menu1').find('li').length;
	for(t = 2; t < index.length; t++ )
		$("#menu1").children().slice(t).remove();
	//alert($('#menu1').html()+" "+index)
	
	var inpLabel = marker1[i1].getAttribute("analogLabel").split("#");
	var inpValue = marker1[i1].getAttribute("analogValue").split("#");
	for(u = 0 ; u < inpLabel.length -1 ; u++)
	{
		//fuelGauge = new Fuel("fuel1");
		//inpLabel[u]
		
		document.getElementById("analogBox"+(u+1)).style.display = "block";
		document.getElementById("head"+(u+1)).innerHTML = inpLabel[u];
		fuelGauge.SetFuel(inpLabel[u]);	
		/*var liTxt = '<li id="AnalogBox'+(u+1)+'" style="display:block;"><a href="#">'+inpLabel[u]+'</a>';
		liTxt += '<ul><li style="background-color:#FFF; padding:5px;">';
		liTxt += '<div id="fuel'+(u+1)+'"><img src="images/needle2.png" alt="needle"/></div>';
		liTxt += '</li></ul></li>';
		//alert(liTxt)*/
		//$("#menu1 ul").append(liTxt);
		/*var container = document.getElementById('menu1');
		// Create a new <li> element for to insert inside <ul id="myList">
		var new_element = document.createElement('li');
		new_element.innerHTML = liTxt;
		container.insertBefore(new_element, container.firstChild);*/
		
		/*
		//$("#menu1 ul").append(liTxt);
		
		alert(liTxt)
		
		//var fuelGauge = new Fuel("fuel"+(u+1));
		//fuelGauge.SetFuel(inpLabel[u]);
		
		//$("#menu1 ul").append("<a href=#>"+inpValue[u]+"</a>")
	}
}
*/
	$('#speedMeter').speedometer({ percentage: Math.round(parseFloat(marker1[i1].getAttribute("speed"))) });
	
	document.getElementById("dateTime").innerHTML='&nbsp;&nbsp;'+marker1[i1].getAttribute("geodate")+" "+marker1[i1].getAttribute("gpsTime");
	var noofSatelite = parseInt(marker1[i1].getAttribute("extraInfo")) ;
	if(noofSatelite >= 5)
		img = 'towe-f';
	else if(noofSatelite <5 && noofSatelite >=3)
	 	img = 'towe-m';
	else if(noofSatelite < 3)
		img = 'towe-w';
	
	if(parseInt(marker1[i1].getAttribute("direction")))
	rotate(parseInt(marker1[i1].getAttribute("direction")), parseInt(2, 10));
	
	document.getElementById("posLatPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("latitude");
	document.getElementById("posLongPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("longitude");
	document.getElementById("posAltPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("altitute");
	document.getElementById("devNameID").innerHTML='&nbsp;'+marker1[i1].getAttribute("deviceName");

}

function updateMarker(i, length, point, markers, speed, direction, gpsTime, geodate, deviceName,
                      deviceIMEI, distance,sessionID, accuracy, isLocationValid, extraInfo,vehiIcon,altitute,latitude,longitude,digInputLabel,digInputValue,digOutputLabel,digOutputValue,analogLabel,analogValue) {
	var divStr = document.getElementById(curId).innerHTML.split("-");
	//alert(speed);
	var icon = new GIcon();
	if(speed > 0)
	{					  
  	    document.getElementById("time_"+curId).innerHTML = geodate+" "+gpsTime;
		document.getElementById(curId).className = "visited_link";
		
		if(direction > 0)
		{
			var arrimg = "compass_"+getCompassImage(direction);
			icon.image = "images/pp/"+arrimg+".gif";		
			icon.iconSize = new GSize(32, 32);
		}
		else
		{
			icon.image = "images/pp/pin30_green_dot.png";
			icon.iconSize = new GSize(18, 22);
		}
	}
	else
	{
		map.clearOverlays();
		//alert(document.getElementById('arrowcanvas').innerHTML);
 	    document.getElementById("time_"+curId).innerHTML = geodate+" "+gpsTime;
		document.getElementById(curId).className = "visited_link";
		
		icon.image = "images/pp/pin30_red_dot.png";
		icon.iconSize = new GSize(18, 22);
	}
		//var label = new ELabel(point, deviceName, "style2");
		//map.addOverlay(label);	
		icon.shadow = "images/pp/pin30_shadow.png";
		icon.shadowSize = new GSize(24, 20);
		icon.iconAnchor = new GPoint(6, 6);
		icon.infoWindowAnchor = new GPoint(20, 10);
		var marker = new GMarker(point,icon);	
		map.setCenter(point, zoomLevel1);

	var addrs;
	var str = "</td></tr>";
	
	var oneDate = gpsTime.split(" ");	

	date = oneDate[0].split("-");
	
	var devTxt='';
	devTxt='<a href=# onclick="onlineGTracker('+sessionID+','+date[0]+','+date[1]+','+date[2]+','+deviceIMEI+');">&nbsp;<strong class=input_submit>View</strong></a>';
	//side_bar_html += '<a href="javascript:myclick(' + (i) + ')">' + deviceName + '<\/a><br>';
	str = "<tr><td align=left colspan=2><strong>Vehicle  : "+deviceName+"</strong></td></tr>";
	
	GEvent.addListener(marker, "click", function() 
	{
		geocoder.getLocations((latitude+","+longitude), function(response)																																						    	{
		  if (!response || response.Status.code != 200) {
				addr="Status Code:" + response.Status.code;
		  }
		  else {
				place = response.Placemark[0];
				addr=place.address;
				
				ajax1.requestFile = '../user/ajax_server.php?FetchUDLoca=1&lat='+latitude+'&lng='+longitude+'&addr='+addr;				
				//alert(ajax1.requestFile);
				ajax1.onCompletion = function()
				{
					addr = ajax1.response;
					//alert(addr+" rrr "+addr1)
					//showMessage(addr)
				
		 
		var ptText='<tr><td colspan=2 align=center><input type=text name="txtMapPoint" id="txtMapPoint" value="Your Geofence Name" />&nbsp;&nbsp;<a href=# onclick="addThisPoint('+latitude+','+longitude+');">&nbsp;<strong class=input_submit>Set</strong></a></td></tr>';
		
		//ListParameters(i,markers);
		//zoomLevel1 = 15;
						
		marker.openInfoWindowHtml(
		
		 "<table class=detailsGrid border=0>"
        //+ "<tr><td align=left>&nbsp;</td><td>&nbsp;</td><td rowspan=2 align=right>"
       // + "<img src=images/" + getCompassImage(direction) + ".jpg alt= />"
        + str
        //+ "<tr><td align=left><b>Speed:</b>:" + speed +  " Kmph&nbsp;</td><td align=left><b>Distance:</b>:"+distance + " Km</td></tr>"
        //+ "<tr><td colspan=2 align=left><b>Date & Time:</b>:" + geodate+"</td></tr>"
        //+ "<tr><td align=left><b>Latitude:</b>:" + latitude + "</td><td align=left><b>Longitude:&nbsp;</b>" + longitude +"</td></tr>"
         + "<tr><td align=left colspan=3><b>Address: </b>:" + addr + "</td></tr>"
		//+ ptText
        + "</table>"
		);
		};
			ajax1.runAJAX();	
		  }
		});
	});

    return marker;
}
function updateAllGPSLocations() 
{
	//data1 = data;
	//responseCode1 = responseCode;
	map.clearOverlays();
	var xmlRoot=GXml.parse(ajax1.response);
	var root = xmlRoot.getElementsByTagName("gps");
	var xml = GXml.parse(ajax1.response);
	var markers = xml.getElementsByTagName("locations");
	var length = markers.length;
	 //progressBar.start(length);
	if(length > 0)
	{
		var otherData = xml.getElementsByTagName("OtherData");
		parameterData = xml.getElementsByTagName("OtherData");
		/*var points2 = [];
		if(otherData[0].getAttribute('totPt')!='')
		{
			var cirPts1 = otherData[0].getAttribute("totPt");	
			
			var ptDt1=cirPts1.split("@");
			
			for(var h = 0; h < (ptDt1.length); h++) {
				  
				ptDt2 = ptDt1[h].split(",");
				points2[h] = new GLatLng(parseFloat(ptDt2[0]),parseFloat(ptDt2[1]));
				
			}
			
			 var poly2= new GPolyline(points2, "#228B22", 2, 1);
			
		}
		 map.addOverlay(poly2);*/
			//myMarker = xml.getElementsByTagName("locations");
		showMessage("Refreshing Map...");
		map.setCenter(new GLatLng(parseFloat(markers[length-1].getAttribute("latitude")),parseFloat(markers[length-1].getAttribute("longitude"))), zoomLevel);	//zoomLevel
	
		for (var i = 0; i < length; i++) 
		{
			callOneMarker(i,map,markers,length);
		}
		showParametersAtPoint(length-1,markers,parameterData)
		//makeClusterMarker(geoData,geoPointName);
		//GEvent.trigger(marker, "click");
	}
	else
	{
		
	}
}
function callOneMarker(p,map,markers,length)
{
	//progressBar.updateLoader(1);
	var point = new GLatLng(parseFloat(markers[p].getAttribute("latitude")),parseFloat(markers[p].getAttribute("longitude")));
	var marker = updateMarker(p, length, point, markers,
						 Math.floor(markers[p].getAttribute("speed")),
						 markers[p].getAttribute("direction"),
						 markers[p].getAttribute("gpsTime"),
						 markers[p].getAttribute("geodate"),
						 markers[p].getAttribute("deviceName"),
						 markers[p].getAttribute("deviceIMEI"),
						 markers[p].getAttribute("distance"),
						 markers[p].getAttribute("sessionID"),
						 markers[p].getAttribute("accuracy"),
						 markers[p].getAttribute("isLocationValid"),
						 markers[p].getAttribute("extraInfo"),
						 markers[p].getAttribute("icon"),
						 parseFloat(markers[p].getAttribute("altitute")),
						 parseFloat(markers[p].getAttribute("latitude")),
						 parseFloat(markers[p].getAttribute("longitude")),
						 markers[p].getAttribute("digInputLabel"),
						 markers[p].getAttribute("digInputValue"),
						 markers[p].getAttribute("digOutputLabel"),
						 markers[p].getAttribute("digOutputValue"),
						 markers[p].getAttribute("analogLabel"),
						 markers[p].getAttribute("analogValue"));
			map.addOverlay(marker);
			GEvent.trigger(marker, "click");

}
function makeClusterMarker(geoData,geoPointName)
{
	var baseIcon = new GIcon();
	baseIcon.image = "images/pushpin-blue.png";
	baseIcon.iconSize=new GSize(22,22);
	baseIcon.iconAnchor=new GPoint(8,8);
	baseIcon.infoWindowAnchor=new GPoint(10,0);
	 
	if(geoData!='')
	{
		var y=0;
		var stName=geoPointName.split(",");
		var gfArr=geoData.split("@");
		for(var f=0;f<(gfArr.length)-1;f++)
		{
			var stopHtml='';
			gpts1=gfArr[f].split(",");
			pnts=new GLatLng(Number(gpts1[1]),Number(gpts1[2]));				
			//var label = new ELabel(pnts, stName[f], "style1");
			//map.addOverlay(label);
			
			var marker5 = createGeo(pnts,baseIcon,'<b>Point Name : </b>'+stName[f]);
			map.addOverlay(marker5);
			
		}
	}
}
var clustmarkers = [];
function loadAllGPSLocations(allDate) 
{
	data = ajax1.response;
	//data1 = data;
	//responseCode1 = responseCode;
	var xml = GXml.parse(data);
	var markers = xml.getElementsByTagName("locations");
		//myMarker = xml.getElementsByTagName("locations");
	showMessage("Loading Map...");
	var length = markers.length;
	if(length > 0)
	{
		var clusticon = new GIcon();
		
		var otherData = xml.getElementsByTagName("OtherData");
		parameterData = xml.getElementsByTagName("OtherData");
		if(otherData[0].getAttribute('geoData')!='' && otherData[0].getAttribute('geoPointName')!='')
		{				
		 	 geoData=otherData[0].getAttribute('geoData');
			 geoPointName=otherData[0].getAttribute('geoPointName');
			 makeClusterMarker(geoData,geoPointName);
		}
		
		map.setCenter(new GLatLng(parseFloat(markers[length-1].getAttribute("latitude")),parseFloat(markers[length-1].getAttribute("longitude"))), zoomLevel);	//zoomLevel
		for (var i = 0; i < length; i++) 
		{
			/*clusticon.image = "../user/unit_img/"+markers[i].getAttribute("icon");
			clusticon.iconSize = new GSize(40, 40);
			clusticon.shadowSize = new GSize(22, 20);
			clusticon.iconAnchor = new GPoint(6, 6);
			clusticon.infoWindowAnchor = new GPoint(20, 20);*/
			
			callAllFunction(i,map,markers,length);
			
			
			//setTimeout('callAllFunction('+i+','+map+','+markers+','+length+')', 10);
			/*var latlng = new GLatLng(parseFloat(markers[i].getAttribute("latitude")),parseFloat(markers[i].getAttribute("longitude")));
			//var label = new ELabel(latlng, markers[i].getAttribute("deviceName"), "style2");
			//map.addOverlay(label);
            var clustmarker = new GMarker(latlng);
			clustmarker.value = markers[i].getAttribute("deviceName");
			GEvent.addListener(clustmarker, "click", function(ll) {
              var mdiv = document.createElement('div');
              mdiv.innerHTML = '<b>Device</b> : ' + this.value;
              this.openInfoWindow(mdiv);
            });*/
            
        }
		var markerCluster = new MarkerClusterer(map, clustmarkers); 
		clustmarkers.length = 0;
		showMessage("Choose device to display navigation");
	}
	else
	{
		showMessage('There is no data to view '+allDate);
	}
}
function toggleRefesh(status)
{
	if(status)
	{
		document.getElementById('spAutoRef').innerHTML =  "Refresh On";
		intervalID = setInterval(function() { 
		txturl = 'showUpdate.php?date_offline='+date_offline + '&sessionID=' + sessionid + '&deviceIMEI=' + devName;
		//refreshMapTable(sessionid,date_offline);
		getOneVehicle(txturl); 
		}, newInterval * 1000);
	}
	else
	{
		document.getElementById('spAutoRef').innerHTML =  "Refresh Off";
		clearInterval(intervalID);
	}
}
var tmpUid = -1;
var intervalID;
var tmpNdiv = '';
var txturl = "";
var curId = -1;
function myclick(sessionid,d1,d2,d3,devName,runflag) 
{
	map.clearOverlays();
	showMessage('Loading...');
	
	pickThisDevice(devName);
	//document.getElementById('totDist').innerHTML = "Null";
	date_offline = d1+"-"+d2+"-"+d3;
	if(intervalID!=0)
	{
		clearInterval(intervalID);
	}
	
	if(gmarkers.indexOf(devName) != -1)
	{
		if(tmpNdiv == '')
		{
			document.getElementById(devName).className = 'visited_link';
			tmpNdiv = devName;
			
		}
		else if(tmpNdiv != devName)
		{
			document.getElementById(tmpNdiv).className = 'green_link';
			document.getElementById(devName).className = 'visited_link';
			tmpNdiv = devName;
		}
		
		refreshSelect.selectedIndex = 4;
		autoRefresh1();
		
	}
	else
	{
		if(tmpNdiv == '')
		{
			document.getElementById(devName).className = 'visited_link';
			tmpNdiv = devName;
			
		}
		else if(tmpNdiv != devName)
		{
			document.getElementById(tmpNdiv).className = 'not_live';
			document.getElementById(devName).className = 'visited_link';
			tmpNdiv = devName;
		}
	
		autoRefresh = 0;
		refreshSelect.selectedIndex = 0;	
		
	}
	
	document.getElementById('from_date').value = date_offline;
	document.getElementById('to_date').value = date_offline;
	txturl = 'showUpdate.php?date_offline='+date_offline + '&sessionID=' + sessionid + '&deviceIMEI=' + devName;
	getOneVehicle(txturl); 
		
	curId = devName;
	document.getElementById('cmdPlay').value = "Play";
	document.getElementById('cmdPlay').disabled = true;
	if(route) clearTimeout(route);
	 stopClick = false;
	 count = 0;
	myMarker = "";
			
}

function callAllFunction(p,map,markers,length)
{

	//progressBar.updateLoader(1);
	var point = new GLatLng(parseFloat(markers[p].getAttribute("latitude")),parseFloat(markers[p].getAttribute("longitude")));
	var marker = createAllMarker(p, length, point, markers,
				 Math.floor(markers[p].getAttribute("speed")),
				 markers[p].getAttribute("direction"),
				 markers[p].getAttribute("gpsTime"),
				 markers[p].getAttribute("geodate"),
				 markers[p].getAttribute("deviceName"),
				 markers[p].getAttribute("deviceIMEI"),
				 markers[p].getAttribute("distance"),
				 markers[p].getAttribute("sessionID"),
				 markers[p].getAttribute("accuracy"),
				 markers[p].getAttribute("isLocationValid"),
				 markers[p].getAttribute("extraInfo"),
				 markers[p].getAttribute("icon"),
				 parseFloat(markers[p].getAttribute("altitute")),
				 parseFloat(markers[p].getAttribute("latitude")),
				 parseFloat(markers[p].getAttribute("longitude")));
	gmarkers[p] = marker;
	imeiArr[p] = markers[p].getAttribute("deviceIMEI");

	// add markers to map
	map.addOverlay(marker);
}

function createAllMarker(i, length, point, allMark, speed, direction, gpsTime, geodate, deviceName,
                      deviceIMEI, distance,sessionID, accuracy, isLocationValid, extraInfo,vehiIcon,altitute,latitude,longitude) {
    var icon = new GIcon();
	//icon.image = "images/RedCar.png";
	//icon.image = "images/car.png";
	/*if(speed > 0)
	{
		
		icon.image = "../user/unit_img/"+vehiIcon;		//"images/gr_arrow3.gif";
		icon.iconSize = new GSize(40, 40);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(19, 2);
		
	}
	else
	{*/
	
		/*if(speed > 0)
		{
		 	var arrimg = "compass_"+getCompassImage(direction);
			icon.image = "images/pp/"+arrimg+".gif";
			icon.iconSize = new GSize(40, 40);
			icon.shadowSize = new GSize(22, 20);
			icon.iconAnchor = new GPoint(6, 6);
			icon.infoWindowAnchor = new GPoint(20, 20);
		}
		else
		{
			icon.image = "images/pp/pin30_red_dot.png";
			icon.iconSize = new GSize(18, 22);
			icon.shadowSize = new GSize(18, 20);
			icon.iconAnchor = new GPoint(10, 20);
			icon.infoWindowAnchor = new GPoint(5, 1);
		}*/
		document.getElementById("time_"+deviceIMEI).innerHTML = geodate+" "+gpsTime;
		icon.image = "../user/unit_img/"+vehiIcon;		//"images/gr_arrow3.gif";
		icon.iconSize = new GSize(40, 40);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 6);
		icon.infoWindowAnchor = new GPoint(20, 20);
		 //var marker = new GMarker(point,icon);
	//}
	var marker = new GMarker(point,icon);
	//var label = new ELabel(point, deviceName, "style1");
	//map.addOverlay(label);
	
	//marker.tooltip = '<div class="infobulle drive"><div class="bg"></div><div class="text"> '+deviceName+'</div></div><div class="arrow"></div>';
	marker.tooltip = '<div class="tooltip">'+deviceName+'<\/div>'
	
	var addrs;
    var str = "</td></tr>";
	
	var oneDate = geodate.split(" ");	
	date = geodate.split("-");

	GEvent.addListener(marker,"mouseover", function() {
          showTooltip(marker);
	});        
	GEvent.addListener(marker,"mouseout", function() {
		tooltip.style.visibility="hidden"
	});
	
	
	var devTxt='';
	devTxt='<a href=# onclick="onlineGTracker('+sessionID+','+date[0]+','+date[1]+','+date[2]+','+deviceIMEI+');">&nbsp;<strong class=input_submit>View</strong></a>';
	
	//side_bar_html += '<a href="javascript:myclick(' + (i) + ')">' + deviceName + '<\/a><br>';
	 
	str = "<tr><td align=left colspan=2><b>Device : "+deviceName+"</b></td></tr>";
	
    GEvent.addListener(marker, "click", function() {
	tooltip.style.visibility="hidden"
	myclick(sessionID,date[0],date[1],date[2],deviceIMEI,'');
	});

    return marker;
}

function createReport(data, responseCode) 
{
	if (data.length == 0) {

        showMessage('There is no tracking data to view.');
        document.getElementById("map_canvas").innerHTML = '';
    }
    else {

	var xml = GXml.parse(data);

	var markers = xml.getElementsByTagName("locations");
	var length = markers.length;
	var reportData = '';
	for (var i = 0; i < (length-1); i++) 
	{
			reportData += i+','+
				 Math.floor(markers[i].getAttribute("speed"))+','+
				 markers[i].getAttribute("direction")+','+
				 markers[i].getAttribute("gpsTime")+','+
				 markers[i].getAttribute("geodate")+','+
				 markers[i].getAttribute("deviceName")+','+
				 markers[i].getAttribute("deviceIMEI")+','+
				 markers[i].getAttribute("sessionID")+','+
				 markers[i].getAttribute("accuracy")+','+
				 markers[i].getAttribute("isLocationValid")+','+
				 markers[i].getAttribute("extraInfo")+','+
				 parseFloat(markers[i].getAttribute("altitute"))+','+
				 parseFloat(markers[i].getAttribute("latitude"))+','+
				 parseFloat(markers[i].getAttribute("longitude"))+"@";
	}
	
	
	//exeReportTable(reportData);
	showMessage('Report Generated');
	}
}
function days_between(date1, date2) {

    var ONE_DAY = 1000 * 60 * 60 * 24

    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

	var difference_ms = date1_ms - date2_ms
	    
    return Math.round(difference_ms/ONE_DAY)

}
function showMapOnDate(sDate,sTime,eDate,eTime,devId) {
	//exeRefreshTable();
	
	document.getElementById('map_canvas').innerHTML = '<center><img src="images/ajax-loader.gif" /></center>';
	var std = sDate.split('-');
	std = new Date(std[2],std[1]-1,std[0]);
	
	var etd = eDate.split('-'); 
	etd = new Date(etd[2],etd[1]-1,etd[0]);
	
	diftd = days_between(etd,std);
	if(diftd <= 6 && diftd >= 0)
	{
		//autoRefresh = 0;
		//alert("int "+intervalID)
		if(intervalID)
		{
			refreshSelect.selectedIndex = 0;
			//autoRefresh1();
			clearInterval(intervalID);
			
		}
		//document.frmMapData.chkShowBubble.disabled = false;
		document.getElementById('selBubbleInter').disabled = false;
		
		sTime = sTime.split(":");
		sTime = (parseInt(sTime[0]*60) + parseInt(sTime[1]));
		
		eTime = eTime.split(":");
		eTime = (parseInt(eTime[0]*60) + parseInt(eTime[1]));
		document.getElementById('showAll').className = 'showlive_on';
		
		showMessage('Loading data...');
		var url = 'locations.php?sDate='+sDate+'&sTime='+sTime+'&eDate='+eDate+'&eTime='+eTime+'&deviceIMEI='+devId;
		ajax1.requestFile = url;
		//document.write(ajax1.requestFile);
		ajax1.onCompletion = function(){hasMap();loadGPSLocations();};
		ajax1.runAJAX();
		//GDownloadUrl(url, loadGPSLocations);
		document.getElementById('cmdPlay').src = "images/icons/play.png";
		//alert(document.getElementById('cmdPlay').src)
		document.getElementById('cmdPlay').alt = "Pause"
	}
	else if(diftd > 6)
	{
		alert("Date difference should be less then or equal to 7");
		showMessage('Date difference should be less then or equal to 7');
	}
	else if(diftd < 0)
	{
		alert("Start Date should not less then End Date");
		showMessage('Start Date should not less then End Date');
	}
}

var map;
// check to see if we have a map loaded, don't want to autorefresh or delete without it
function hasMap()
{
	if (GBrowserIsCompatible())
	{
	        map = new GMap2(document.getElementById("map_canvas"));
	        //map.addControl(new GLargeMapControl());
			var extLargeMapControl = new ExtLargeMapControl();
	        map.addControl(extLargeMapControl);
	        map.addControl(new GMenuMapTypeControl());
		    map.enableScrollWheelZoom();
		   //map.enableContinuousZoom();
		    map.addControl(new GScaleControl());
			//progressBar = new ProgressbarControl(map, {width:150}); 
			//map.setUIToDefault();
			//map.addControl(new GOverviewMapControl());

			if(mapType=="Map" || mapType=="")
			{
				//mapType=map.getCurrentMapType().getName();
				map.setMapType(G_NORMAL_MAP);
			}
			else if(mapType=="Satellite")
			{
				mapType=map.getCurrentMapType().getName();
				map.setMapType(G_SATELLITE_MAP); 
			}
			else if(mapType=="Hybrid")
			{
				mapType=map.getCurrentMapType().getName();
				map.setMapType(G_HYBRID_MAP); 
			}
			
			GEvent.addListener(map, "maptypechanged", function() {		
				mapType=map.getCurrentMapType().getName();
				
			})
			GEvent.addListener(map, "zoomend", function() {
					zoomLevel1 = map.getZoom();
			});
			
			tooltip = document.createElement("div");
		    document.getElementById("map_canvas").appendChild(tooltip);
		    tooltip.style.visibility="hidden";
			
			
        return true;
	 }
	 else
	 {
		 return false;
	 }
}
function changeType(id)
{
		//alert(id);
		//left_pan('side_pan', 'control_pan');
		mapType=id;
		if(mapType==1)
		map.setMapType(G_NORMAL_MAP);
		else if(mapType==2)
		map.setMapType(G_SATELLITE_MAP); 
		else if(mapType==3)
		map.setMapType(G_HYBRID_MAP);
}
function showBubbleInterval(val)
{
	//bubInter = val
	//alert(bubInter)
	/*if(document.getElementById('chkShowBubble').checked)
	{
		mapPoints=5;
		document.getElementById('shBub').innerHTML='Hide Bubble';
		
	}
	else
	{
		mapPoints=2;
		document.getElementById('shBub').innerHTML='Show Bubble';
	}*/
	//loadGPSLocations();	
}
function showPoints()
{
	if(document.getElementById('chkShowBubble').checked)
	{
		mapPoints=5;
		document.getElementById('shBub').innerHTML='Hide Bubble';
		
	}
	else
	{
		mapPoints=2;
		document.getElementById('shBub').innerHTML='Show Bubble';
	}
	loadGPSLocations();	
}
function funcHideStop()
{
	//alert(document.getElementById('chkHidStop').checked);
	if(document.getElementById('chkHidStop').checked)
	{
		hsp=1;
		document.getElementById('stopHead').innerHTML='Show Stop Points';
		loadGPSLocations(data1, responseCode1);

	}
	else
	{
		hsp=0;
		document.getElementById('stopHead').innerHTML='Hide Stop Points';
		loadGPSLocations(data1, responseCode1);
	}
}
var points = [];

function loadGPSLocations() 
{
	if(ajax1.response)
		data1 = ajax1.response;
	else
		data1 = data1;

	var totalStop=0;
	var c1=0;
	var d1;
	var dis=0;

       
	map.clearOverlays();
	var xml=GXml.parse(data1);
	var geoData="";
	var geoPointName="";
	myMarker ="";
	var root = xml.getElementsByTagName("gps");
	
	// create list of GPS data locations from our XML

	// markers that we will display on Google map
	var data = xml.getElementsByTagName("locations");
	myMarker = xml.getElementsByTagName("locations");
	
	var length = data.length;
	if(length >0)
	{
	
		var otherData = xml.getElementsByTagName("OtherData");
		parameterData = xml.getElementsByTagName("OtherData");
		/*if(otherData[0].getAttribute('geoData')!='')
		{
			 geoData=otherData[0].getAttribute('geoData');
		}
		if(otherData[0].getAttribute('geoPointName')!='')
		{
			 geoPointName=otherData[0].getAttribute('geoPointName');
		}*/
		if(otherData[0].getAttribute('geoPointName')!='')
		{
			cirPts = otherData[0].getAttribute("totPt");	
			var ptDt1=cirPts.split("@");
			var totalDistance=0;
			
			for(var h = 0; h < (ptDt1.length)-1; h++) {
				  
				ptDt2 = ptDt1[h].split(",");
				points[h] = new GLatLng(parseFloat(ptDt2[0]),parseFloat(ptDt2[1]));
				
			}
		}
		if(otherData[0].getAttribute('totalDist')!='')
		{
			 //document.getElementById('totDist').innerHTML = otherData[0].getAttribute('totalDist') +" km(s)";;
		}

		
		//progressBar.start(length);
		t1=data.length;
		// center map on last marker so we can see progress during refreshes
		if(zoomLevel1)
		{
			map.setCenter(new GLatLng(parseFloat(data[length-1].getAttribute("latitude")),parseFloat(data[length-1].getAttribute("longitude"))), zoomLevel1);
		}
		else 
		{
			 map.setCenter(new GLatLng(parseFloat(data[length-1].getAttribute("latitude")),parseFloat(data[length-1].getAttribute("longitude"))), zoomLevel);
		}
	

	/*var icon = new GIcon();
	icon.image = "http://www.google.com/intl/en_de/mapfiles/ms/icons/ltblue-dot.png";
	addIcon(icon);*/
	
	
	  var points1 =[];
	  var reportData = '';
	  
	  //callFunction(0,map,data,length);
	  //points1[0] = new GLatLng(parseFloat(data[0].getAttribute("latitude")), parseFloat(data[0].getAttribute("longitude")));	 
	  //playMarkId.push(0);
		  for(var i = 0; i < data.length; i++) 
		  {
			points1[i] = new GLatLng(parseFloat(data[i].getAttribute("latitude")), parseFloat(data[i].getAttribute("longitude")));	
			//if(Math.floor(data[i].getAttribute("speed")) > 0) 
			if(tmpDist ==-1 || tmpDist != Math.floor(data[i].getAttribute("distance")) )
			{
				tmpDist = Math.floor(data[i].getAttribute("distance"));
				callFunction(i,map,data,length,otherData);
				playMarkId.push(i);
			
			
			reportData += i+','+
				 Math.floor(data[i].getAttribute("speed"))+','+
				 data[i].getAttribute("direction")+','+
				 data[i].getAttribute("gpsTime")+','+
				 data[i].getAttribute("geodate")+','+
				 data[i].getAttribute("deviceName")+','+
				 data[i].getAttribute("deviceIMEI")+','+
				 data[i].getAttribute("sessionID")+','+
				 data[i].getAttribute("accuracy")+','+
				 data[i].getAttribute("isLocationValid")+','+
				 data[i].getAttribute("extraInfo")+','+
				 parseFloat(data[i].getAttribute("altitute"))+','+
				 parseFloat(data[i].getAttribute("latitude"))+','+
				 parseFloat(data[i].getAttribute("longitude"))+"@";
			}
		  }
		  j = length - 1;
		  playMarkId.push(j);
		  points1[j] = new GLatLng(parseFloat(data[j].getAttribute("latitude")), parseFloat(data[j].getAttribute("longitude")));	
		  animLinePt  = points1
		  callFunction(j,map,data,length,parameterData);
		  showParametersAtPoint(j,data,parameterData);
		  makeClusterMarker(geoData,geoPointName);
		  // Draw polylines between marker points
		  var poly= new GPolyline(points1, "#090", 2.5, 0.8);
		  map.addOverlay(poly);

		  //exeReportTable(reportData);
	}
	else
	{
		showMessage('There is no tracking data to view on the specified time.');
	}
}
function callFunction(p,map,markers,length,paramData)
{
	var point = new GLatLng(parseFloat(markers[p].getAttribute("latitude")),parseFloat(markers[p].getAttribute("longitude")));
	var marker = createMarker(p, length, point,markers,paramData,
				 Math.floor(markers[p].getAttribute("speed")),
				 markers[p].getAttribute("direction"),
				 markers[p].getAttribute("gpsTime"),
				 markers[p].getAttribute("geodate"),
				 markers[p].getAttribute("deviceName"),
				 markers[p].getAttribute("deviceIMEI"),
				 markers[p].getAttribute("distance"),
				 markers[p].getAttribute("sessionID"),
				 markers[p].getAttribute("accuracy"),
				 markers[p].getAttribute("isLocationValid"),
				 markers[p].getAttribute("extraInfo"),
				 parseFloat(markers[p].getAttribute("altitute")),
				 parseFloat(markers[p].getAttribute("latitude")),
				 parseFloat(markers[p].getAttribute("longitude")));
	
	// add markers to map
	map.addOverlay(marker);
	//GEvent.trigger(marker, "click");
}
function showParametersAtPoint(i1,marker1,paramData)
{
deleteRow('paramTable')
document.getElementById("fuel1").style.display = "none";
document.getElementById("fuel2").style.display = "none";
document.getElementById("analogTitle1").innerHTML = "";
document.getElementById("analogTitle2").innerHTML = "";
document.getElementById("analogTitle1").className = "";
document.getElementById("analogTitle2").className = "";

var str = marker1[i1].getAttribute("other");
//var devmodel = marker1[i1].getAttribute("deviceModel");
/*if(marker1[i1].getAttribute("fuelPort") != 0)
{
	var fuel = getDataFromParam(str,marker1[i1].getAttribute("fuelPort"));

	if(fuel.length >= 3)
	{
		fuelVal = marker1[i1].getAttribute("fuelVoltage").split("@")
		fuelLtr = marker1[i1].getAttribute("fuelLtr").split("@")

		finVal =  getClosestElement(fuelVal, fuelLtr, (fuel/1000)) ;
		fuelGauge.SetFuel(finVal);
	}
	else
	{
		fuelGauge.SetFuel(0);
	}
}
else
{
	$('li#fuelIMG').hide();
}*/
var table = document.getElementById('paramTable');
 
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
cell1.innerHTML = "<b>Distance</b>";

var cell2 = row.insertCell(1);
cell2.innerHTML = marker1[i1].getAttribute("distance")+" km(s)";

if(marker1[i1].getAttribute("Parameter"))
{
	var str = marker1[i1].getAttribute("Parameter");
	
	if(paramData[0].getAttribute('inPort'))
	{
		var inPort = paramData[0].getAttribute('inPort');
		inPort1 = inPort.split("#");
		
		var dispParam = "";
		
		for(k=0; k<(inPort1.length)-1;k++)
		{
			inPort2 = inPort1[k].split("_");
		
			if(inPort2[1] != 0)
			{
				//alert(k+" "+otherPort2[k]+" "+otherPort3)
				var res = getDataFromParam(str,inPort2[1]);
				var table = document.getElementById('paramTable');
		
				var rowCount = table.rows.length;
				var row = table.insertRow(rowCount);
		
				var cell1 = row.insertCell(0);
				cell1.innerHTML = "<b>"+inPort2[0]+"</b>";
		
				var cell2 = row.insertCell(1);
				cell2.innerHTML = '<img src=images/icons/on-'+res+'.png width=20 height=20 border=0 />';
		
			}
		}
	}
	if(paramData[0].getAttribute('analogPort'))
	{
		var analogPort1 = paramData[0].getAttribute('analogPort');
		analogPort = analogPort1.split("@");
		for(var k=0;k<analogPort.length-1;k++)
		{						
			d1 = analogPort[k].split("=");
			
			
			
			var element1 = document.createElement("input");
 			element1.type = "text";
			element1.name = "txtBox";
			element1.id = "txtBox";
			element1.value = d1[0];
			//Assign different attributes to the element.
		 
			//var foo = document.getElementById("analogTitle"+(k+1));
		 	//$("analogTitle"+(k+1)).append('<p>Test</p>');
			//Append the element in page (in span).
			//foo.appendChild(element1);
			
	
			d2 = d1[1].substr(0,d1[1].indexOf("("));
			n = d1[1].indexOf("(")+1;
			d3 = d1[1].substr(n).replace(")",""); 		
			d3 = d3.split("#");
			var fuelValue = getDataFromParam(str,d2);
			
			var vol =  new Array();
			var ltr = new Array();
			for(l = 0; l < d3.length-1; l++)
			{
				d4 = d3[l].split("_");
				vol[l]=d4[1];
				ltr[l]=d4[0];
			}
			if(vol.length >0 && ltr.length > 0)
			{
				finVal =  getClosestElement(vol, ltr, (fuelValue/1000));
				var n = k+1;
				document.getElementById("fuel"+(k+1)).style.display = "block";
				var fuelObj = new Fuel("fuel1");
				document.getElementById("analogTitle"+n).className = "thHead";
				document.getElementById("analogTitle"+n).innerHTML = d1[0];
				//alert(document.getElementById("analogTitle"+(k+1)).innerHTML)
				fuelGauge.SetFuel(50);
			}
		}	
	}
	//else document.getElementById("fuel"+(k+1)).style.display = "none";
}
	//alert(Math.round(parseFloat(marker1[i1].getAttribute("speed"))))
	$('#speedMeter').speedometer({ percentage: Math.round(parseFloat(marker1[i1].getAttribute("speed"))) });
	
	//document.getElementById("dateTime").innerHTML='&nbsp;&nbsp;'+marker1[i1].getAttribute("geodate");
	var noofSatelite = parseInt(marker1[i1].getAttribute("extraInfo")) ;
	if(noofSatelite >= 5)
		img = 'towe-f';
	else if(noofSatelite <5 && noofSatelite >=3)
	 	img = 'towe-m';
	else if(noofSatelite < 3)
		img = 'towe-w';
	
	if(parseInt(marker1[i1].getAttribute("direction")))
		rotate(parseInt(marker1[i1].getAttribute("direction")), parseInt(2, 10));
	
	//document.getElementById("posLatPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("latitude");
	//document.getElementById("posLongPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("longitude");
	//document.getElementById("posAltPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("altitute");
	//document.getElementById("devNameID").innerHTML='&nbsp;'+marker1[i1].getAttribute("deviceName");

}
function createMarker(i, length, point, markers,paramData, speed, direction, gpsTime, geodate, deviceName,deviceIMEI, distance,sessionID, accuracy, isLocationValid, extraInfo,altitute,latitude,longitude) 
{
    var icon = new GIcon();
	if ((i == length -1 )  && (mapPoints==2 || mapPoints==1 || mapPoints==5))
	{
		
		var canvas = document.getElementById("arrowcanvas").getContext('2d');
		canvas.clearRect(0, 0, 32, 32);
		//var newIcon = MapIconMaker.createLabeledMarkerIcon({width: 12, height: 15, addStar: true, label: "C", primaryColor: "#ff0000"});
		icon.image = "marker/icons/dd-end.png";
		//icon.shadow = "images/coolshadow_small.png";
		icon.iconSize = new GSize(18, 22);
			

	}
	else if(i == 0 && (mapPoints==2 || mapPoints==1 || mapPoints==5) )
	{	
			//var newIcon = MapIconMaker.createLabeledMarkerIcon({width: 12, height: 15, addStar: true, label: "S", primaryColor: "#00ff00"});
			icon.image = "marker/icons/dd-start.png";
			//icon.shadow = "images/coolshadow_small.png";
			icon.iconSize = new GSize(18, 22);
	}
	else if( (mapPoints==1 || mapPoints==5))
	{
			//var newIcon = MapIconMaker.createLabeledMarkerIcon({width: 10, height: 10, addStar: false, label: "45", primaryColor: "#0FC0FF"});
			 if(speed == 0)
			 pimg = "pin30_red_dot";
			 else if(speed > 0 && speed < 60)
				pimg = "pin30_blue_"+getCompassImage(direction);
			 else if(speed > 60)
				pimg = "pin30_yellow_"+getCompassImage(direction);
	
				icon.image = "images/pp/"+pimg+".png";
				//icon.shadow = "images/pin30_shadow.png";
				icon.iconSize = new GSize(18, 22);
			
	}
	icon.shadow = "images/pin30_shadow.png";
	icon.shadowSize = new GSize(18, 20);
	icon.iconAnchor = new GPoint(10, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	myGMarker[i] = new GMarker(point,icon);
	
	//var newIcon = MapIconMaker.createLabeledMarkerIcon({addStar: true, label: "a", primaryColor: "#00ff00"});
 
	var latlng;
	// this describes how we got our location data, either by satellite or by cell phone tower
  
    var str = "</td></tr>";

    // when a user clicks on last marker, let them know it's final one
    if (i == length - 1) {
        str = "</td></tr><tr><th align=center colspan=2>Final location</th></tr>";
    }
	else if (i == 0) {
        str = "</td></tr><tr><th align=center colspan=2>Start point</td></tr>";
    }

	// this creates the pop up bubble that displays info when a user clicks on a marker
    GEvent.addListener(myGMarker[i], "click", function() 
	{
		showParametersAtPoint(i,markers,paramData);
	geocoder.getLocations((latitude+","+longitude), function(response)																																						     {
	  if (!response || response.Status.code != 200) {
		//alert("Status Code:" + response.Status.code);
	  }
	  else {
			place = response.Placemark[0];
			addr=place.address;
			//addr=addr.split(",");
			
	  		ajax1.requestFile = '../user/ajax_server.php?FetchUDLoca=1&lat='+latitude+'&lng='+longitude+'&addr='+addr;				
			//alert(ajax1.requestFile);
			ajax1.onCompletion = function()
			{
				addr = ajax1.response;
				
	
	var str= "</td></tr><tr><td align=left colspan=2><b>Device : "+deviceName+"</b></td></tr>";
	var ptText='<tr><td colspan=2 align=center><input type=text name="txtMapPoint" id="txtMapPoint" value="Your Geofence Name" />&nbsp;&nbsp;<a href=# onclick="addThisPoint('+latitude+','+longitude+');">&nbsp;<strong class=input_submit>Set</strong></a></td></tr>';
	  
        myGMarker[i].openInfoWindowHtml(
		 "<table class=detailsGrid border=0>"
        //+ "<tr><td align=left>&nbsp;</td><td>&nbsp;</td><td rowspan=2 align=right>"
       // + "<img src=images/" + getCompassImage(direction) + ".jpg alt= />"
        + str
        + "<tr><td align=left><b>Speed:</b>:" + speed +  " Kmph&nbsp;</td><td align=left><b>Distance:</b>:"+distance + " Km</td></tr>"
        + "<tr><td colspan=2 align=left><b>Date & Time:</b>:" + geodate+"</td></tr>"
        + "<tr><td align=left><b>Latitude:</b>:" + latitude + "</td><td align=left><b>Longitude:&nbsp;</b>" + longitude +"</td></tr>"
        + "<tr><td align=left colspan=3><b>Address: </b>:" + addr + "</td></tr>"
		//+ ptText
        + "</table>"
       
        );
			};
		ajax1.runAJAX();	
		}
		});
    });
	
    return myGMarker[i];
}
function addIcon(icon) { // Add icon properties

 icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
 icon.iconSize = new GSize(32, 32);
 icon.shadowSize = new GSize(37, 34);
 icon.iconAnchor = new GPoint(15, 34);
 icon.infoWindowAnchor = new GPoint(19, 2);
 icon.infoShadowAnchor = new GPoint(18, 25);
}
function addClickevent(marker) { // Add a click listener to the markers

 GEvent.addListener(marker, "click", function() {
  marker.openInfoWindowHtml(marker.content);
  /* Change count to continue from the last manually clicked marker
  *  Better syntax since Javascript 1.6 - Unfortunately not implemented in IE.
  *  count = gmarkers.indexOf(marker);
  */
  count = marker.nr;
  stopClick = true;
 });
 return marker;
}
var count =0;
var stopClick = false;

var animLinePt = [];
function playAnimation(playBtnObj)
{
	if(playBtnObj.alt == "Pause")
	{
		playBtnObj.alt = "Play";
		playBtnObj.src= "images/icons/pause.png";
		showMessage('Point Animation Started ...');
		if(count == 0)
		map.clearOverlays();
		var poly = new GPolyline(animLinePt, "#090", 2, 1);
		map.addOverlay(poly);
		anim();
		document.getElementById('cmdStop').src= "images/icons/stop.png";
		document.getElementById('cmdStop').alt= "Stop";
	}
	else if(playBtnObj.alt == "Play")
	{
		playBtnObj.src= "images/icons/play.png";
		playBtnObj.alt= "Pause";
		showMessage('Point Animation Paused ...');
		haltAnim();
		document.getElementById('cmdStop').src= "images/icons/stop.png";
		document.getElementById('cmdStop').alt= "Stop";
	}
	
}
function haltAnim() 
{
 if(route) {
  clearTimeout(route);
  stopClick = true;
 }
}
function stopAnimation(playBtnObj) 
{
 if(route && playBtnObj.alt == "Stop") 
 {
	document.getElementById('cmdPlay').src= "images/icons/d_play.png";
	document.getElementById('cmdStop').src= "images/icons/d_stop.png";
	document.getElementById('cmdPlay').alt= "t_Play";
	clearTimeout(route);
	count = myMarker.length-1;
	route = null;
	//anim();
	map.clearOverlays();
	callOneMarker(count,map,myMarker,myMarker.length);
	GEvent.trigger(myGMarker[count], "click");
 }
}
function createPlayMarker(p,map,markers,length,paramData)
{
	//progressBar.updateLoader(1);
	var point = new GLatLng(parseFloat(markers[p].getAttribute("latitude")),parseFloat(markers[p].getAttribute("longitude")));
	map.panTo(point);
	var marker = createMarker(p, length, point,markers,paramData,
				 Math.floor(markers[p].getAttribute("speed")),
				 markers[p].getAttribute("direction"),
				 markers[p].getAttribute("gpsTime"),
				 markers[p].getAttribute("geodate"),
				 markers[p].getAttribute("deviceName"),
				 markers[p].getAttribute("deviceIMEI"),
				 markers[p].getAttribute("distance"),
				 markers[p].getAttribute("sessionID"),
				 markers[p].getAttribute("accuracy"),
				 markers[p].getAttribute("isLocationValid"),
				 markers[p].getAttribute("extraInfo"),
				 parseFloat(markers[p].getAttribute("altitute")),
				 parseFloat(markers[p].getAttribute("latitude")),
				 parseFloat(markers[p].getAttribute("longitude")));
	
	// add markers to map
	map.addOverlay(marker);
	GEvent.trigger(marker, "click");

}

function anim() 
{
	if(count < playMarkId.length)
	{
		ncot = playMarkId[count];
		createPlayMarker(ncot,map,myMarker,myMarker.length,parameterData);
		//GEvent.trigger(myGMarker[ncot], "click");
		//animLinePt[ncot] = new GLatLng(parseFloat(myMarker[ncot].getAttribute("latitude")), parseFloat(myMarker[ncot].getAttribute("longitude")));	
		
		
		// Draw polylines between marker points
		if(count == 0)
			var delay = 0;
		else 
			var delay = document.getElementById('selBubbleInter').value *1000;
		//callFunction(count,map,myMarker,myMarker.length);
		
		count++;
		route = setTimeout("anim()", delay);
	}
	else 
	{
		clearTimeout(route);
		count = 0;
		document.getElementById('cmdPlay').src= "images/icons/play.png";
		document.getElementById('cmdStop').src= "images/icons/d_stop.png";
		document.getElementById('cmdPlay').alt= "Pause";
		showMessage('Point Animation Completed.');
		route = null;
	}
}
function showCirclePts(type,ptData)
{
	//alert(ptData);
	var pts = [];
	var ptDt1=ptData.split("@");
	for(var f=0;f<(ptDt1.length)-1;f++)		//(ptDt1.length)-1
	{
		ptDt2 = ptDt1[f].split(",");
		pts[f] = new GLatLng(parseFloat(ptDt2[0]),parseFloat(ptDt2[1]));
		//alert(pts[f]);
	}
	//pts[ptDt1.length] = new GLatLng(parseFloat(ptDt2[0]),parseFloat(ptDt2[1]));
	//alert(pts[ptDt1.length-2]+" "+ptDt1.length);
	var poly = new BDCCArrowedPolyline(pts,"#FF0000",1,0.60,null,1,7,"#0000FF",1,0);
	map.addOverlay(poly);
}
function createCircle (centerHandlePosition,radius,color)
{
    var points = [];
    var distance = radius/1000;
    for (i = 0; i < 72; i++) {
      points.push(destination(centerHandlePosition, i * 360/72, distance) );
    }
    points.push(destination(centerHandlePosition, 0, distance) );
    //this._polyline = new GPolyline(this._points, this._color, 6);
    var polyline = new GPolygon(points, color, 1, 1, color, 0.2);
    map.addOverlay(polyline)
    //this._control.render();
}
function destination(orig, hdng, dist) {
  var R = 6371; // earth's mean radius in km
  var oX, oY;
  var x, y;
  var d = dist/R;  
  hdng = hdng * Math.PI / 180; // degrees to radians
  oX = orig.x * Math.PI / 180;
  oY = orig.y * Math.PI / 180;

  y = Math.asin( Math.sin(oY)*Math.cos(d) + Math.cos(oY)*Math.sin(d)*Math.cos(hdng) );
  x = oX + Math.atan2(Math.sin(hdng)*Math.sin(d)*Math.cos(oY), Math.cos(d)-Math.sin(oY)*Math.sin(y));

  y = y * 180 / Math.PI;
  x = x * 180 / Math.PI;
  return new GLatLng(y, x);
}
function createGeo(point4,icon4,html4) {
	//alert(point4+","+icon4+","+html4);
	var marker5 = new GMarker(point4,{icon:icon4});
	GEvent.addListener(marker5, "mouseover", function() {
   geocoder.getLocations(point4, function(response)																																						   {
	  if (!response || response.Status.code != 200) {
        //alert("Status Code:" + response.Status.code);
		addr="Status Code:" + response.Status.code;
      }
	  else {
        	place = response.Placemark[0];
			//addr=place.address;
			//alert(place.address);
			//addr=addr[0]+","+addr[1]+","+place.AddressDetails.Country.CountryNameCode;
		//alert(place.address);
	  }
	
  	html5="<table class=detailsGrid border=0>"
	+ "<tr><td align=left>" + html4 +  "</td><td valign=top align=left><img src=../../images/favicon.png /></td></tr>"
	+ "<tr><td align=left colspan=2><b>Location:</b>&nbsp;" + place.address + "</td></tr>"
	+ "</table>"
	
  	  marker5.openInfoWindowHtml(html5);
	  });

  });
	return marker5;
}	
function funFindDura(spt,ept)
{
	var ptf=0;
	if(spt == '' && ept == '')
	{
		alert('Please select the values');
		ptf=0;
		document.getElementById('txtFrmPt').select();
	}
	else if(spt == '' )
	{
		alert('Please select start point');
		ptf=0;
		document.getElementById('txtFrmPt').select();
		document.getElementById('txtFrmPt').value='';
	}
	else if(!ptno.test(spt))
	{
		alert('From should be integer');
		ptf=0;
		document.getElementById('txtFrmPt').focus();
		document.getElementById('txtFrmPt').value='';
	}

	else if( ept == '')
	{
		alert('Please select end point');
		ptf=0;
		document.getElementById('txtToPt').select();
		document.getElementById('txtToPt').value='';

	}
	else if(!ptno.test(ept))
	{
		alert('To should be integer');
		ptf=0;
		document.getElementById('txtToPt').value='';
		document.getElementById('txtToPt').focus();
	}
	else if(spt > t1 || ept > t1)
	{
		alert('Out of range.Please enter 0 to '+t1);
		ptf=0;
		document.getElementById('txtFrmPt').select();
		document.getElementById('txtFrmPt').value='';
		document.getElementById('txtToPt').value='';
	}
	//else if(spt >= ept)
//	{
//		alert('From should be less than To');
//		ptf=0;
//		document.getElementById('txtFrmPt').select();
//		document.getElementById('txtFrmPt').value='';
//		document.getElementById('txtToPt').value='';
//	}
	else ptf++;

	if(ptf!=0)
	{
		//alert(t1);
		findDuration(map,myMarker,spt,ept);		
		document.getElementById('txtFrmPt').value='';
		document.getElementById('txtToPt').value='';
		document.getElementById('txtFrmPt').focus();
	}else return false;
}
function findDuration(map,myMarker,spt,ept)
{
	var length2 = myMarker.length;
	var dis1=0;
	var t5=0.0;
	var t6=0.0;
	var tmp1=0;
	var dur=null;
	var init=null;
	var spt1=null;
	var ept1=null;
	var t2=0;

		spt1=myMarker[spt].getAttribute("gpsTime");
		ept1=myMarker[ept].getAttribute("gpsTime");
		
	dur=Math.abs(diffTime(spt1,ept1));
	//alert(dur);
	if(dur <  3600)
	{
		alert("Time taken from point 1 to point 2 is : "+Math.round(dur/60)+" Mins");
	}
	else
	{
		hr1=Math.floor(dur/3600);
		mn1=dur-(3600*hr1);
		mn1=Math.floor(mn1/60);

		//alert(hr1);
		alert("Time taken from point 1 to point 2 is : "+hr1+" Hour and "+mn1+" Mins");
	}
}


function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}


function getDataFromParam(str,portNo)
{
	var ind3 = str.split(" ");
	for(h=0;h<ind3.length-1;h++)
	{
		var findPort = "["+portNo+"=";
		if(ind3[h].indexOf(findPort) > -1)
		{
			var ind4 = ind3[h].replace("]","");
			ind4 = ind4.replace(findPort,"");
			return ind4;
			break;
			//ind4 = ind4.substr(findPort.length)
			//alert(findPort+" "+ind4)
		}
	}
	
	//var ind2=str.substr(ind1);
	
	//alert(portNo+" TTT "+ind3)
	/*for(i = 0; i < mySplitResult.length; i++)
	{
		s = mySplitResult[i];
		ac1 = s.substr(0,4).replace(/^\s+|\s+$/g,"")
		if(ac1=='[2='){
		  ac2=s.substr(4);
		   if(ac2=='1'){
			  ac3 = 'on';
		  } else {
			 ac3 = 'off';
		  }
		}		
	}*/
}
function deleteRow(tableID) {
	try {
	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;
	for(var i=0; i<rowCount; i++) {
			table.deleteRow(i);
			rowCount--;
			i--;
	}
	}catch(e) {
		//alert(e);
	}
	
	//document.getElementById('analogBox1').style.display= 'none';
	//document.getElementById('analogBox2').style.display= 'none';
}

function getClosestElement(fuelVal, fuelltr, value) 
{
	tmp = -1;
	if (fuelVal.length > 0) 
	{
		//echo max($array)."<br><br>";
		//$ret = max($array);
		 for (v = 0; v < fuelVal.length; v++) //list(key, va) = each(array)
		 {			 
			 diff = Math.abs(fuelVal[v] - value);			
			 if(tmp == -1)
			 {
				 tmp = diff;
				 k = fuelltr[v];
				 //echo "1st ".$key." & ".$diff." = ".$value." diff ".$tmp."<br><br><br>";
				
			 }
			 else
			 {
				 //echo $key." & ".$diff." = ".$value." diff ".$tmp."<br>";
				 if(tmp > diff) 
				 {
					 tmp = diff;
					 k = fuelltr[v];
				 }
			}
		}
		//echo "<br> ".$key." ".$va." & ".$diff." = ".$value." diff ".$tmp."<br>";
		//var x= (100)/(fuelltr[fuelltr.length-1]);
		return k;
		//echo "<br><br>";
	}
	else 
	{
	  return NULL;
	}
	
}
function showParameters(i1,marker1)
{
deleteRow('paramTable')
var str = marker1[i1].getAttribute("other");
var devmodel = marker1[i1].getAttribute("deviceModel");
if(marker1[i1].getAttribute("fuelPort") != 0)
{
	var fuel = getDataFromParam(str,marker1[i1].getAttribute("fuelPort"));

	if(fuel.length >= 3)
	{
		fuelVal = marker1[i1].getAttribute("fuelVoltage").split("@")
		fuelLtr = marker1[i1].getAttribute("fuelLtr").split("@")

		finVal =  getClosestElement(fuelVal, fuelLtr, (fuel/1000)) ;
		fuelGauge.SetFuel(finVal);
	}
	else
	{
		fuelGauge.SetFuel(0);
	}
}
else
{
	$('li#fuelIMG').hide();
}
var otherPort1 = marker1[i1].getAttribute("otherPort");
//alert(fuelPort)
otherPort2 = otherPort1.split("#");
var dispParam = "";

for(k=0; k<(otherPort2.length)-1;k++)
{
	otherPort3 = otherPort2[k].split("_");

	if(otherPort3[1] != 0)
	{
		//alert(k+" "+otherPort2[k]+" "+otherPort3)
		var resultPort = getDataFromParam(str,otherPort3[1])
		if(resultPort == 1)
		{
			var table = document.getElementById('paramTable');
 
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
 
            var cell1 = row.insertCell(0);
			cell1.innerHTML = "<b>"+otherPort3[0]+"</b>";
 
            var cell2 = row.insertCell(1);
            cell2.innerHTML = '<img src=images/icons/ignition-on.png width=20 height=20 border=0 />';

			//dispParam += '<img src=images/icons/ignition-on.png width=20 height=20 border=0 />';
		}
		else if(resultPort == 0)
		{
			var table = document.getElementById('paramTable');
 
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
 
            var cell1 = row.insertCell(0);
			cell1.innerHTML = "<b>"+otherPort3[0]+"</b>";
 
            var cell2 = row.insertCell(1);
            cell2.innerHTML = '<img src=images/icons/ignition-off.png width=20 height=20 border=0 />';
			//dispParam += '<img src=images/icons/ignition-off.png width=20 height=20 border=0 />';
		}
	}
	
}
var table = document.getElementById('paramTable');
 
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
cell1.innerHTML = "<b>Distance</b>";

var cell2 = row.insertCell(1);
cell2.innerHTML = marker1[i1].getAttribute("distance")+" km(s)";
//alert(dispParam)
//document.getElementById('otherParam').innerHTML = dispParam;
//alert(str)


	//document.getElementById("distance").innerHTML="Traveled&nbsp;&nbsp; "+Math.round(totalDistance)+" Km";
	//document.getElementById("ctSpd").innerHTML='&nbsp;&nbsp;'+Math.round(parseFloat(marker1[i1].getAttribute("speed")))+' kmph';
	$('#speedMeter').speedometer({ percentage: Math.round(parseFloat(marker1[i1].getAttribute("speed"))) });
	
	document.getElementById("dateTime").innerHTML='&nbsp;&nbsp;'+marker1[i1].getAttribute("geodate");
	var noofSatelite = parseInt(marker1[i1].getAttribute("extraInfo")) ;
	if(noofSatelite >= 5)
		img = 'towe-f';
	else if(noofSatelite <5 && noofSatelite >=3)
	 	img = 'towe-m';
	else if(noofSatelite < 3)
		img = 'towe-w';
	
	rotate(parseInt(marker1[i1].getAttribute("direction")), parseInt(2, 10));
	
	//document.getElementById("noSate").innerHTML='&nbsp;<img src=images/icons/'+img+'.gif width=40 height=20 border=0 />';
	document.getElementById("posLatPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("latitude");
	document.getElementById("posLongPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("longitude");
	document.getElementById("posAltPt").innerHTML='&nbsp;'+marker1[i1].getAttribute("altitute");
	document.getElementById("devNameID").innerHTML='&nbsp;'+marker1[i1].getAttribute("deviceName");
	//document.getElementById("totDist").innerHTML='&nbsp;'+marker1[i1].getAttribute("distance")+" km(s)";
	
    //document.getElementById("Fuel").innerHTML='Fuel&nbsp;&nbsp;'+marker1[i1].getAttribute("fuel");
	//document.getElementById("other").innerHTML=marker1[i1].getAttribute("other");	

}

var ajax1=new sack();
var stopName=/^[a-zA-Z0-9][a-zA-Z0-9 ]*$/;

function validThis()
{
 	if(document.getElementById('txtMapPoint').value=="")
	{
		alert('Stop Name required');
		document.getElementById('txtMapPoint').focus();
		return false;
	}
	else if (!stopName.test(document.getElementById('txtMapPoint').value)) 
	{
		alert('Only alphanumeric allowed');
		document.getElementById('txtMapPoint').focus();
		document.getElementById('txtMapPoint').select();
		return false;	
	}
	else
	{
		return true;
	}
}
function getPolyLatLngs(latlng) {
  var mapNormalProj = G_NORMAL_MAP.getProjection();
  var mapZoom = map.getZoom();
  var centerPixel = mapNormalProj.fromLatLngToPixel(latlng, mapZoom);

  var polyNumSides = 6;
  var polySideLength = 60;
  var polyRadius = 40;
  var polyLatLngs = [];
  for (var a = 0; a<(polyNumSides+1); a++) {
	var aRad = polySideLength*a*(Math.PI/180);
	var pixelX = centerPixel.x + polyRadius * Math.cos(aRad);
	var pixelY = centerPixel.y + polyRadius * Math.sin(aRad);
	var polyPixel = new GPoint(pixelX,pixelY);
	var polyLatLng = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
	polyLatLngs.push(polyLatLng);
  }
  return polyLatLngs;
}
function addThisPoint(lt1,lng1)
{
	var flg1=validThis();
	var latlng = lt1+","+lng1;
	//var latlng = new GLatLng(parseFloat(lt1),parseFloat(lng1));
	//var polyLatLngs = getPolyLatLngs(latlng);
	if(flg1)
	{
		ajax1.requestFile = 'ajax_server.php?add_stop_name='+document.getElementById('txtMapPoint').value+'&mapPt='+latlng;
		//alert(ajax1.requestFile);
		ajax1.onCompletion = function(){
		if(ajax1.response == 0)
		{
			alert('Same point name already exist. Please use different.');
			document.getElementById('txtMapPoint').focus();
			document.getElementById('txtMapPoint').select();
		}
		else
		{
			alert("Point added successfully.");
			map.closeInfoWindow();
		}
		};
		ajax1.runAJAX();
	}
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
// this chooses the proper image for our litte compass in the popup window
function getCompassImage(azimuth) {
    if ((azimuth >= 337 && azimuth <= 360) || (azimuth >= 0 && azimuth < 23))
            return "h0";
    if (azimuth >= 23 && azimuth < 68)
            return "h1";
    if (azimuth >= 68 && azimuth < 113)
            return "h2";
    if (azimuth >= 113 && azimuth < 158)
            return "h3";
    if (azimuth >= 158 && azimuth < 203)
            return "h4";
    if (azimuth >= 203 && azimuth < 248)
            return "h5";
    if (azimuth >= 248 && azimuth < 293)
            return "h6";
    if (azimuth >= 293 && azimuth < 337)
            return "h7";

    return "";
}


function autoRefresh1() 
{
    if (true) 
	{
        newInterval = refreshSelect.options[refreshSelect.selectedIndex].value;
        if (currentInterval > 0) { // currently running at an interval

            if (newInterval > 0) { // moving to another interval (3)
			
                clearInterval(intervalID);
               intervalID = setInterval(function() { 
							getOneVehicle(txturl); 
							}, newInterval * 1000);
                currentInterval = newInterval;
            }
            else { // we are turning off (2)
                clearInterval(intervalID);
                newInterval = 0;
                currentInterval = 0;
            }
        }
        else { // off and going to an interval (1)
		
            intervalID = setInterval(function() { 
							getOneVehicle(txturl); 
							}, newInterval * 1000);
            currentInterval = newInterval;
        }

        showMessage(refreshSelect.options[refreshSelect.selectedIndex].innerHTML);
        //setTimeout('showRouteName();', 5000);
  	}
	else {
	    alert("Please select a route before trying to refresh map.");
	    refreshSelect.selectedIndex = 0;
	}
}


function changeZoomLevel() {
    if (hasMap()) {
        zoomLevel = zoomLevelSelect.selectedIndex + 1;

        getRouteForMap();

        // show what zoom level action was taken and after 5 seconds, display the route name again
        showMessage(zoomLevelSelect.options[zoomLevelSelect.selectedIndex].innerHTML);
        setTimeout('showRouteName();', 5000);
  	}
	else {
	    alert("Please select a route before selecting zoom level.");
	    zoomLevelSelect.selectedIndex = zoomLevel - 1;
	}
}

function showMessage(message) {
     messages.innerHTML = 'Status: ' + message;
}

function hideWait() {
    map.innerHTML = '';
    messages.innerHTML = 'Status:';
}


